package br.com.rumus.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import br.com.rumus.jpa.EMUtil;

public class DAOGenerico<T, PK extends Serializable> implements DAO<T, PK>{
	
    protected Class<T> tipo;
    private EntityManager entityManager;

    @SuppressWarnings("unchecked")
	public DAOGenerico() {
        this.tipo = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        this.entityManager = EMUtil.getEntityManager();
    }

    @SuppressWarnings("unchecked")
	public List<T> listar(){
        return entityManager.createQuery("select entidade from " + tipo.getSimpleName() + " entidade").getResultList();
    }

    public T buscar(PK pk){
        return entityManager.find(tipo, pk);
    }

    public void inserir(T entidade){
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.persist(entidade);
        transaction.commit();
    }

    public void alterar(T entidade){
    	EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.merge(entidade);
        transaction.commit();
    }

    public void remover(T entidade){
        Object toRemove = entityManager.merge(entidade);
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.remove(toRemove);
        transaction.commit();
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

}